define(['jquery-magnify'], function() {
    angular.module('app.imageviewer', [])
        .directive('imageviewer', imageViewerDirective);

    function imageViewerDirective($timeout) {
        return {
            restrict: 'E',
            replace: true,
            template: '<div class="image-viewer">' +
                      '  <a data-magnify="gallery" ng-href="{{href}}">' +
                      '    <img ng-src="{{src}}">' +
                      '  </a>' +
                      '</div>',
            scope: {
                file: '=',
                context: '='
            },
            link: function(scope, element) {
                var path = encodeURIComponent(scope.file.path);
                scope.href = scope.src = '/note/file/preview?file=' + path;
                // load image
                $timeout(function() {
                    $('a', element).magnify({
                        resizable: false,
                        initMaximized: true,
                        title: false,
                        headerToolbar: [],
                        footerToolbar: [
                            'fullscreen',
                            'zoomIn',
                            'zoomOut',
                            'rotateLeft',
                            'rotateRight',
                            'actualSize'
                        ],
                        callbacks: {
                            opened: function(context) {
                                $('a', element).replaceWith(context.$magnify);
                            }
                        }
                    }).trigger('click');
                });

                scope.file.renderer = function() {
                    // navbar
                    scope.context.navbar['file']['save'].enabled = false;
                    scope.context.navbar['edit']['undo'].enabled = false;
                    scope.context.navbar['edit']['redo'].enabled = false;
                    scope.context.navbar['edit']['cut'].enabled = false;
                    scope.context.navbar['edit']['copy'].enabled = false;
                    scope.context.navbar['edit']['paste'].enabled = false;
                    // statusbar
                    scope.context.statusbar.link = scope.file.path;
                    scope.context.statusbar.statuses = ['只读'];
                }

                // destroy
                scope.$on('$destroy', function() {
                    element.remove();
                });
            }
        };
    }
});
